﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using wms.Common;

namespace wms.Pages
{
    /// <summary>
    /// RecordInList.xaml 的交互逻辑
    /// </summary>
    public partial class RecordInList : Page
    {
        private int pageNo = 1;
        private int pagePer = 5000;
        private int pages = 1;
        private DataTable _dt = null;

        public RecordInList()
        {
            ChangeLanguage.changePage(Variable.LanguageSeesion.ToString());
            ChangeLanguage.changePage(Variable.LanguageSeesion.ToString());
        }

        private void btn_query_Click(object sender, RoutedEventArgs e)
        {

            int? state = null;
            if (this.rdo_verify_1.IsChecked == true)
            {
                state = 2;
            }
            else if (this.rdo_verify_2.IsChecked == true)
            {
                state = 1;
            }
            bool exact = this.cbx_exact.IsChecked == true;

            query(this.txt_record_number.Text, this.txt_transactor.Text, Utils.ParseDateTime(this.txt_time_begin.Text != "" ? Convert.ToDateTime(this.txt_time_begin.Text).ToString("yyyy-MM-dd HH:mm:ss") : this.txt_time_begin.Text), Utils.ParseDateTime(this.txt_time_end.Text != "" ? Convert.ToDateTime(this.txt_time_end.Text).ToString("yyyy-MM-dd HH:mm:ss") : this.txt_time_end.Text),
                this.txt_type.Text, state, exact);
        }


        private void query(string record_number, string transactor, DateTime? create_time_begin, DateTime? create_time_end, string type, int? state, bool exact)
        {
            Dictionary<string, object> param = new Dictionary<string, object>();
            string sql = "select t.*, (case t.state when 1 then '未审核' when 2 then '已审核' end) state_text from t_record_in t where 1 = 1";
            if (!string.IsNullOrWhiteSpace(record_number))
            {
                sql += " and record_number = @record_number";
                param.Add("@record_number", record_number);
            }
            if (!string.IsNullOrWhiteSpace(transactor))
            {
                if (exact)
                {
                    sql += " and transactor = @transactor";
                }
                else
                {
                    sql += " and transactor like '%' + @transactor + '%' ";
                }
                param.Add("@transactor", transactor);
            }
            if (create_time_begin != null)
            {
                sql += " and create_time >= @create_time_begin";
                param.Add("@create_time_begin", create_time_begin);
            }
            if (create_time_end != null)
            {
                sql += " and create_time <= @create_time_end";
                param.Add("@create_time_end", create_time_end);
            }
            if (!string.IsNullOrWhiteSpace(type))
            {
                sql += " and type = @type";
                param.Add("@type", type);
            }
            if (state != null)
            {
                sql += " and state = @state";
                param.Add("@state", state);
            }

            this._dt = DBHelper.GetDataTable(sql, param, "id", pagePer, (pageNo - 1) * pagePer);
            dataGrid.ItemsSource = this._dt.DefaultView;
            int count = DBHelper.GetCount(sql, param);

            this.pages = (count + pagePer - 1) / pagePer;
            //this.lbl_page.Content = String.Format("共{0}条 每页{1}条，当前{2}/{3}", count, pagePer, pageNo, pages);

            this.dataGrid2.ItemsSource = null;
        }

        private void btn_add_Click()
        {
            new RecordInInput().Show();
        }

        private void dataGrid_MouseDoubleClick(object sender = null, MouseButtonEventArgs e = null)
        {
            DataRowView drv = this.dataGrid.SelectedItem as DataRowView;
            if (drv != null)
            {
                RecordInInput rii = new RecordInInput(Utils.ParseInt(drv["id"]));
                rii.Show();
                //rii.Closed += Gi_Closed;
            }
        }

        private void btn_update_Click()
        {
            dataGrid_MouseDoubleClick();
        }

        private void btn_delete_Click()
        {
            string message = "";
            IList drv = this.dataGrid.SelectedItems as IList;
            if (drv.Count > 0 && MessageBox.Show("确定删除选中物品？", "提示", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                foreach (var item in drv)
                {
                    DataRow dr = (item as DataRowView).Row;
                    int? id = Utils.ParseInt(dr["id"]);
                    int? state = Utils.ParseInt(dr["state"]);
                    if (id != null && state != null && state == 1)
                    {
                        DBHelper.ExcuteSQL("delete t_record_in where id = " + id);
                        DBHelper.ExcuteSQL("delete t_record_in_item where record_in_id = " + id);

                    }
                    else
                    {
                        message += "入库单号【" + dr["record_number"].ToString() + "】，已审核，不能删除！" + "\r\n";
                    }
                }
                query("", "", null, null, null, null, false);
                if (message != "")
                {
                    MessageBox.Show(message);
                    return;
                }
            }
            else
            {
                MessageBox.Show("没有选中项");
            }
        }

        private void btn_refresh_Click()
        {
            query("", "", null, null, null, null, false);
        }

        private void dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                this.btnBar.ButtonDelete.IsEnabled = this.dataGrid.SelectedIndex == -1 ? false : true;
                this.btnBar.ButtonModify.IsEnabled = this.dataGrid.SelectedIndex == -1 ? false : true;
                this.btnBar.ButtonVerify.IsEnabled = false;
                DataRowView drv = this.dataGrid.SelectedItem as DataRowView;
                if (drv != null)
                {
                    int? id = Utils.ParseInt(drv["id"]);
                    int? state = Utils.ParseInt(drv["state"]);
                    if (state == 1)
                    {
                        this.btnBar.ButtonVerify.IsEnabled = true;
                    }
                    DataTable dt = DBHelper.GetDataTable("select t.id,t.record_in_id,t.goods_id,t.quantity,t.memo,t2.name,t2.code,t2.client,t2.[size],t2.type,t2.[value],t2.weight from t_record_in_item t inner join t_goods t2 on t.goods_id = t2.id where t.record_in_id = " + id);
                    this.dataGrid2.ItemsSource = dt.AsDataView();
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
        }

        private void dataGrid_Loaded(object sender, RoutedEventArgs e)
        {
            dataGrid_SelectionChanged(null, null);
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            query("", "", null, null, null, null, false);
        }

        private void btn_verify_Click()
        {
            DataRowView drv = this.dataGrid.SelectedItem as DataRowView;
            if (drv != null && MessageBox.Show("确认审核通过？", "提示", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                int? id = Utils.ParseInt(drv["id"]);
                int? state = Utils.ParseInt(drv["state"]);
                if (id != null && state != null && state == 1)
                {
                    int r = DBHelper.ExcuteSQL("update t_record_in set state = 2 where id = " + id);
                    if (r == 1)
                    {
                        drv["state"] = 2;
                        drv["state_text"] = "已审核";
                        return;

                    }
                }
                else
                {
                    MessageBox.Show("记录不存在或已经审核");
                }
            }
            else
            {
                MessageBox.Show("没有选中项");
            }
        }

        private void btn_export_Click()
        {

            if (this._dt == null)
            {
                MessageBox.Show("没有数据可以导出");
                return;
            }

            Dictionary<string, string> mapping = new Dictionary<string, string>();
            mapping.Add("record_number", "入库单号");
            mapping.Add("type", "入库类型");
            mapping.Add("create_time", "业务日期");
            mapping.Add("transactor", "经办人");
            mapping.Add("state_text", "审核状态");
            mapping.Add("describe", "说明");
            mapping.Add("memo", "备注");
            mapping.Add("modify_user", "修改人");
            mapping.Add("modify_time", "修改时间");

            System.Windows.Forms.SaveFileDialog sd = new System.Windows.Forms.SaveFileDialog();
            sd.Filter = "Excel 2003 文档|*.xls";
            if (sd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (File.Exists(sd.FileName))
                {
                    File.Delete(sd.FileName);
                }
                ExcelHelper.TableToExcel(this._dt, mapping, sd.FileName);
                if (MessageBox.Show("导出完毕，是否现在打开？", "提示", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    System.Diagnostics.Process.Start(sd.FileName);
                }
            }
        }

        private void labelYWRQ_MouseDown(object sender, MouseButtonEventArgs e)


        {
            TextBlock text = sender as TextBlock;
            int? flag = text.Tag as int?;

            if (flag == null || flag == 1)
            {
                DateTime dt = DateTime.Now;
                this.txt_time_end.Text = dt.ToString("yyyy-MM-dd HH:mm:ss");
                dt = dt.AddDays(-dt.Day + 1);
                this.txt_time_begin.Text = DateTime.Now.AddDays(-DateTime.Now.Day + 1).ToString("yyyy-MM-dd HH:mm:ss");
                text.Tag = 2;
            }
            else if (flag == 2)
            {
                DateTime dt = DateTime.Now;
                dt = dt.AddMonths(-1);
                dt = dt.AddDays(-dt.Day + 1);
                this.txt_time_begin.Text = dt.ToString("yyyy-MM-dd HH:mm:ss");
                dt = dt.AddMonths(1);
                dt = dt.AddDays(-1);
                this.txt_time_end.Text = dt.ToString("yyyy-MM-dd HH:mm:ss");
                text.Tag = 3;
            }
            else if (flag == 3)
            {
                DateTime dt = DateTime.Now;
                DateTime dtb = dt.AddDays(-1);
                this.txt_time_begin.Text = dtb.ToString("yyyy-MM-dd HH:mm:ss");
                this.txt_time_end.Text = dt.ToString("yyyy-MM-dd HH:mm:ss");
                text.Tag = 1;
            }
            else
            {
                text.Tag = 1;
            }
        }
    }
}
